package com.fyl.utils;

import com.fyl.dto.BaseTreeDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class BaseTreeUtil {

    public static <T, R extends BaseTreeDTO> List<R> build(Function<T, R> mapper, List<T> list) {
        List<R> temp = list.stream().map(mapper).collect(Collectors.toList());
        List<Object> childIds = findChildIds(temp);
        List<R> r = new ArrayList<>();
        for (R o : temp) {
            if (Objects.isNull(o.getParentId()) || !childIds.contains(o.getId())) {
                o.findChildren(temp);
                r.add(o);
            }
        }
        return r;
    }

    private static <R extends BaseTreeDTO> List<Object> findChildIds(List<R> trees) {
        List<Object> childIds = new ArrayList<>();
        loop:
        for (int i = 0; i < trees.size(); i++) {
            R c = trees.get(i);
            if (Objects.isNull(c.getParentId())) {
                continue;
            }
            for (int j = 0; j < trees.size(); j++) {
                R p = trees.get(j);
                if (c.getParentId().equals(p.getId())) {
                    childIds.add(c.getId());
                    continue loop;
                }
            }
        }
        return childIds;
    }
}
